﻿#include "textinput.h"
#include "encoding.h"
#include "sqlite3.h"
#include "def.h"
//////////////////////////////////////////////////////////////////////////
// implement KeyboardNotificationLayer
//////////////////////////////////////////////////////////////////////////

KeyboardNotificationLayer::KeyboardNotificationLayer()
: m_pTrackNode(0),pTextField(0)
{
    setIsTouchEnabled(true);
}

void KeyboardNotificationLayer::registerWithTouchDispatcher()
{
    CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, false);
}

void KeyboardNotificationLayer::keyboardWillShow(CCIMEKeyboardNotificationInfo& info)
{
    /*  CCLOG("TextInputTest:keyboardWillShowAt(origin:%f,%f, size:%f,%f)",
     info.end.origin.x, info.end.origin.y, info.end.size.width, info.end.size.height);
     */
    if (! m_pTrackNode)
    {
        return;
    }
    
    CCRect rectTracked = getRect(m_pTrackNode);
    /* CCLOG("TextInputTest:trackingNodeAt(origin:%f,%f, size:%f,%f)",
     rectTracked.origin.x, rectTracked.origin.y, rectTracked.size.width, rectTracked.size.height);*/
    
    // if the keyboard area doesn't intersect with the tracking node area, nothing need to do.
    if (! CCRect::CCRectIntersectsRect(rectTracked, info.end))
    {
        return;
    }
    
    // assume keyboard at the bottom of screen, calculate the vertical adjustment.
    float adjustVert = CCRect::CCRectGetMaxY(info.end) - CCRect::CCRectGetMinY(rectTracked);
    //CCLOG("TextInputTest:needAdjustVerticalPosition(%f)", adjustVert);
    
    // move all the children node of KeyboardNotificationLayer
    CCArray * children = getChildren();
    CCNode * node = 0;
    int count = children->count();
    CCPoint pos;
    for (int i = 0; i < count; ++i)
    {
        node = (CCNode*)children->objectAtIndex(i);
        pos = node->getPosition();
        pos.y += adjustVert;
        node->setPosition(pos);
    }
}

// CCLayer function

bool KeyboardNotificationLayer::ccTouchBegan(CCTouch *pTouch, CCEvent *pEvent)
{
    //CCLOG("++++++++++++++++++++++++++++++++++++++++++++");
    m_beginPos = pTouch->locationInView(pTouch->view());	
    m_beginPos = CCDirector::sharedDirector()->convertToGL(m_beginPos);
    return true;
}

void KeyboardNotificationLayer::ccTouchEnded(CCTouch *pTouch, CCEvent *pEvent)
{
	
    if (! m_pTrackNode)
    {
        return;
    }
    CCPoint endPos = pTouch->locationInView(pTouch->view());	
    endPos = CCDirector::sharedDirector()->convertToGL(endPos);
    
    float delta = 5.0f;
    if (::abs(endPos.x - m_beginPos.x) > delta
        || ::abs(endPos.y - m_beginPos.y) > delta)
    {
        // not click
        m_beginPos.x = m_beginPos.y = -1;
        return;
    }
    
    // decide the trackNode is clicked.
    CCRect rect;
    CCPoint point = convertTouchToNodeSpaceAR(pTouch);
    //CCLOG("KeyboardNotificationLayer:clickedAt(%f,%f)", point.x, point.y);
    
    rect = getRect(m_pTrackNode);
    //CCLOG("KeyboardNotificationLayer:TrackNode at(origin:%f,%f, size:%f,%f)",
    //    rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
    
    this->onClickTrackNode(CCRect::CCRectContainsPoint(rect, point));
    
	//CCLOG("---------------%s----------------",pTextField->getString());
    
}


//////////////////////////////////////////////////////////////////////////
// implement TextInput
//////////////////////////////////////////////////////////////////////////

std::string TextInput::subtitle()
{
    return "TextFieldTTF with default behavior test";
	//this->getContentText;
}

void TextInput::onClickTrackNode(bool bClicked)
{
    pTextField = (CCTextFieldTTF*)m_pTrackNode;
	
    if (bClicked)
    {
        // TextFieldTTFTest be clicked
        CCLOG("TextInput:CCTextFieldTTF attachWithIME");
        pTextField->attachWithIME();
		
    }
    else
    {
        // TextFieldTTFTest not be clicked
        CCLOG("TextInput:CCTextFieldTTF detachWithIME");
        pTextField->detachWithIME();
    }
}

void TextInput::onEnter()
{
    KeyboardNotificationLayer::onEnter();
    
    // add CCTextFieldTTF
    CCSize s = CCDirector::sharedDirector()->getWinSize();
    
    pTextField = CCTextFieldTTF::textFieldWithPlaceHolder(" ",
                                                          FONT_NAME,
                                                          FONT_SIZE);
	
	pTextField->setColor(ccc3(255, 255, 255));
    addChild(pTextField);
	
    
	
#if (CC_TARGET_PLATFORM == CC_PLATFORM_ANDROID)	
	// on android, CCTextFieldTTF cannot auto adjust its position when soft-keyboard pop up
	// so we had to set a higher position to make it visable
	pTextField->setPosition(ccp(s.width / 2, s.height/2 + 50));
#else
	pTextField->setPosition(ccp(s.width / 2, s.height / 2));
#endif
    
    m_pTrackNode = pTextField;
    
	//Add menu button
	//CCLabelTTF* label = CCLabelTTF::labelWithString(wchar2utf8(L"保存").c_str(), "Arial", 18);
	//CCMenuItemLabel* pSaveItem = CCMenuItemLabel::itemWithLabel(label, this, menu_selector(TextInput::onSave));
	//CCMenu* pMenu = CCMenu::menuWithItems(pSaveItem, NULL);
	//pMenu->setPosition( ccp(s.width-20, s.height-20) );
	//this->addChild(pMenu, 1);
}
//void TextInput::menuSaveCallback(CCObject* pSender)

void TextInput::onSave(CCObject* pSender)
{
    
	sqlite3 *pDB = NULL;
	char * msg = NULL;
	int ret;
	char * sql = "create table if not exists messages (msgid integer PRIMARY KEY autoincrement, msgtext TEXT  NULL,synflag  integer DEFAULT 0 NULL)";
    
	//如果不存在会自动创建
	ret = sqlite3_open(getdbfile(), &pDB);
	//CCLog("sqlite3_open ret=%d",ret);
    
	ret = sqlite3_exec(pDB, sql, NULL, NULL, &msg);
	//CCLog("exec [%s] ret=%d msg=%s",sql,ret,msg);
	
	const char* tmp = pTextField->getString();
	int tmpLen=  strlen(tmp);
    
	char line[1024]={'\0'};
	char quote[2]={'\"'};
	char *sep = "\r\n";
	int wordCounter = 0; //字符计数器
	int wordPerLine = 10; //每行的英文字符数
	for(int i=0; i<tmpLen; i++)
	{
		if(tmp[i]>0) //SQLite中UTF8汉字由3个字节组成 且首字节小于0
		{ 
			if(tmp[i]==0x27){ //单引号 替换成双引号
				memcpy(line+strlen(line),quote,1);
			}
			else{
				memcpy(line+strlen(line),tmp+i,1);
			}
			wordCounter++;
		}
		else
		{
			memcpy(line+strlen(line),tmp+i,3);
			wordCounter+=2; //显示时约定一个汉字占用2个英文字母的宽度
			i+=2;
		}
        
		if(wordCounter>=wordPerLine)
		{
			memcpy(line+strlen(line),sep,2);
			wordCounter = 0;
		}
	}
    
	//CCLog("%s",line);
    
	char sqlisert[1024]={'\0'};   
	sprintf( sqlisert, "insert into messages(msgtext) values('%s')", line);   // pTextField->getString()默认即UTF-8无需转码
	
    
	ret = sqlite3_exec(pDB, sqlisert, NULL, NULL, &msg);
	CCLog("exec [%s] ret=%d msg=%s",sqlisert,ret,msg);
    
	sqlite3_close(pDB);
    
    
	//CCTouchDispatcher::sharedDispatcher()->addTargetedDelegate(this, 0, false);
	CCTouchDispatcher::sharedDispatcher()->removeDelegate(this);
	this->autorelease();
}


void TextInput::onQuit(CCObject* pSender)
{
    
	
}

void TextInput::onExit()
{
	
}